package com.dkm.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.JpaSort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.dkm.entity.Counselor;
import com.dkm.entity.DynamicMessage;
import com.dkm.entity.Users;
import com.dkm.service.CounselorService;
import com.dkm.service.DynamicMessageService;
import com.dkm.service.UsersService;
import com.dkm.util.LayuiJsonUilt;
import com.dkm.util.ResultUtil;

@RestController
@RequestMapping("/dynamicMessage")
public class DynamicMessageController {

	//注入动态消息业务层
	@Autowired
	private DynamicMessageService dynamicMessageService;
	//注入咨询师业务层
	@Autowired
	private CounselorService counselorService;
	@Autowired
	private UsersService usersService;
	
	@GetMapping
	public LayuiJsonUilt<DynamicMessage> findAllDynamicMessages(String user_id,LayuiJsonUilt<DynamicMessage> lj) {
		Map<String, Object> map=new HashMap<String, Object>();
		
		if(user_id!=null&&user_id!="") {
			//根据用户id获取咨询师
			Counselor counselor=counselorService.getCounselorByUser_id(user_id);
			//存入咨询师姓名
			if(counselor!=null) {
				map.put("recipient", counselor.getCounselor_name());
			}else {
				//加入用户登录名
				Users user=usersService.getUserById(user_id);
				map.put("recipient", user.getLogin_name());
			}
		}
		//排序 按时间降序
		Sort sort=JpaSort.unsafe(Sort.Direction.DESC, "\\Qcreate_time\\E");
		//创建pageable对象
		Pageable pageable=PageRequest.of(lj.getPage(), lj.getLimit(), sort);
		//获取jpa的page对象
		Page<DynamicMessage> p=dynamicMessageService.findAllDynamicMessages(map, pageable);
		
		//设置数据和数据长度
		lj.setData(p.getContent());
		lj.setCount(p.getTotalElements());
		
		return lj;
	}
	
	@PostMapping
	public ResultUtil addDynamicMessage(String sid,DynamicMessage dynamicMessage) {
		
		return dynamicMessageService.addDynamicMessage(sid,dynamicMessage);
	}
	
	@PutMapping
	public ResultUtil updateDynamicMessage(DynamicMessage dynamicMessage) {
		
		return dynamicMessageService.updateDynamicMessage(dynamicMessage);
	}
}
